import React, { Component } from 'react';
import store from '../../store';
import { getInitList, getInputChangeAction, getAddItemAction, getDeleteItemAction } from '../../store/actionCreators';
import TodoItemUI from './TodoItemUI';
import { message } from 'antd';

class TodoList extends Component {
	constructor(props) {
	    super(props);
			this.state = store.getState();
			this.handleInputChange = this.handleInputChange.bind(this);
			this.handleKeyUpItemAdd= this.handleKeyUpItemAdd.bind(this);
			this.handleStoreChange = this.handleStoreChange.bind(this);
			this.handleItemAdd = this.handleItemAdd.bind(this);
			this.handleItemDelete = this.handleItemDelete.bind(this);
			store.subscribe(this.handleStoreChange);
	}
	
	componentDidMount() {
		// 不用中间件的最初的代码
		// axios.get('/mocker/test.json').then(res => {
		// 	const action = initTodoList(res.data.list);
		// 	store.dispatch(action);
		// })
		
		// 以下是使用redux-thunk的代码
		// const action = getTodoList();
		// store.dispatch(action);
		
		// redux-saga
		const action = getInitList();
		// 用了redux-saga之后，派发的action不仅reducer能接收，saga.js也能接收
		store.dispatch(action);
	}
	
	componentWillUnmount() {
		this.setState = (state, callback) => {
			return;
		}
	}
	
	handleStoreChange() {
		this.setState(store.getState());
	}
	
	handleInputChange(e) {
		const action = getInputChangeAction(e.target.value);
		store.dispatch(action);
	}
	
	handleKeyUpItemAdd(e) {
		if (e.keyCode === 13) {
			this.handleItemAdd();
		}
	}
	
	handleItemAdd() {
		if (this.state.inputValue === '') {
			message.error('请输入内容');
			return;
		}
		const action = getAddItemAction();
		store.dispatch(action);
	}
	
	handleItemDelete(index) {
		const action = getDeleteItemAction(index);
		store.dispatch(action);
	}
	
	render() {
		const { inputValue, list } = this.state;
		return (
			<TodoItemUI
				inputValue={inputValue}
				list={list}
				handleInputChange={this.handleInputChange}
				handleKeyUpItemAdd={this.handleKeyUpItemAdd}
				handleItemAdd={this.handleItemAdd}
				handleItemDelete={this.handleItemDelete}
			/>
		)
	}
}

export default TodoList;